import { defineConfig, ConfigEnv, UserConfig, loadEnv } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import path from 'path'
// vite.config.ts中无法使用import.meta.env 所以需要引入
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// 增加 vue文件 script name值
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
// 生产gz文件
import viteCompression from 'vite-plugin-compression'
import legacy from '@vitejs/plugin-legacy'

const Timestamp = new Date().getTime()

function resolve(dir: string) {
  return path.join(__dirname, '.', dir)
}

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  return {
    plugins: [
      vue(),
      legacy({
        targets: [
          'defaults',
          'not IE 11',
          'iOS >= 10',
          'Android >= 6',
          'Chrome >= 49',
          'Safari >= 10',
        ],
      }),
      vueSetupExtend(),
      // * 使用 svg 图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      // gzip压缩 生产环境生成 .gz 文件
      mode === 'production' &&
        viteCompression({
          verbose: true,
          disable: false,
          threshold: 10240,
          algorithm: 'gzip',
          ext: '.gz',
        }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/index.scss" as *;`,
        },
      },
    },
    // 配置别名
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        static: resolve('public/static'),
      },
      // 忽略后缀名的配置选项, 添加 .vue 选项时要记得原本默认忽略的选项也要手动写入
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
    },
    server: {
      host: '0.0.0.0',
      port: 8088,
      open: true,
      proxy: {
        // 开发环境
        [loadEnv(mode, process.cwd()).VITE_APP_BASE_API]: {
          target: 'http://192.168.3.2:7116', // easymock
          changeOrigin: true,
          ws: true,
          // rewrite: path => path.replace(/^\/dev-api/, ''),
          rewrite: (path) => {
            const apiString = loadEnv(mode, process.cwd()).VITE_APP_BASE_API
            const envApi = new RegExp(apiString, 'g')
            return path.replace(envApi, '')
          },
        },
      },
    },
    build: {
      outDir: 'chantWeb',
      terserOptions: {
        compress: {
          drop_console: false,
          drop_debugger: false,
        },
      },
      sourcemap: false, // 输出.map文件,默认是false
      rollupOptions: {
        output: {
          chunkFileNames: `static/js/[name].[hash]${Timestamp}.js`,
          entryFileNames: `static/js/[name].[hash]${Timestamp}.js`,
          assetFileNames: `static/[ext]/[name].[hash]${Timestamp}.[ext]`,
        },
      },
    },
    define: {
      __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false',
    },
  }
})
